//
//  DisposeAlarmVC.m
//  efairy
//  处理报警信息
//  Created by 李锋 on 2019/2/28.
//  Copyright © 2019年 East. All rights reserved.
//

#import "AlarmDisposeVC.h"
#import "AddDisposeAlarmInfoListCell.h"
#import "AddDisposeAlarmCell.h"
#import "SeeMoreAlarmBtnCell.h"
#import "EFAMatAddImgTCell.h"
#import "EFAModel.h"
#import "ApiManager.h"
#import "XDQiniuManager.h"
#import "AddImgCell.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "GlobalHeader.h"


@interface AlarmDisposeVC ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate,AddImgCellDelegate>
@property(nonatomic,strong) UIButton *closeUpBtn;
//@property(nonatomic,strong) UIButton *footerBtn;
@property(nonatomic,strong) UIView *footerView;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,assign)float navigationbarH;
@property (strong, nonatomic) NSArray *typeArray;
@property (nonatomic, strong) EFAAlarmPubModel *pubModel;
@property(nonatomic,strong) AlarmNoDispostIdListModel *disposeIdModel;
@property(nonatomic,assign)NSInteger alarmTypeValue;
@property(nonatomic,strong) NSMutableArray<NSNumber *> *alarmCellArray;
@property(nonatomic,assign) int index;
@property(nonatomic,assign) int allRows;
@property(nonatomic,strong) NSMutableArray<AlarmNoDispostListModel *> *showAlarmArray;

@end

@implementation AlarmDisposeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationbar];
    _index = 0;
    _alarmCellArray= [NSMutableArray arrayWithCapacity:3];
    [_alarmCellArray addObject:@(0)];
    [_alarmCellArray addObject:@(0)];
    [_alarmCellArray addObject:@(0)];
    if(_showAlarmArray == nil){
         _showAlarmArray = [[NSMutableArray alloc]init];
    }
   
   
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setNavigationbar{
    self.navigationItem.title = @"新增报警处理";
}

-(void)initView{
     _navigationbarH = self.navigationController.navigationBar.frame.size.height;
    _closeUpBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, statusBarHeight+_navigationbarH, SCREEN_WIDTH, 40)];
    _closeUpBtn.backgroundColor = [UIColor whiteColor];
    [_closeUpBtn setTitle:@"合上" forState:UIControlStateNormal];
    [_closeUpBtn setImage:[UIImage imageNamed:@"icon_see_more_close"] forState:UIControlStateNormal];
    _closeUpBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [_closeUpBtn setTitleColor:ColorFromRGB(0x666666) forState:UIControlStateNormal];
    [_closeUpBtn addTarget:self action:@selector(onclickClose) forControlEvents:UIControlEventTouchUpInside];
    [_closeUpBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -_closeUpBtn.imageView.size.width, 0, _closeUpBtn.imageView.size.width)];
    [_closeUpBtn setImageEdgeInsets:UIEdgeInsetsMake(0, _closeUpBtn.titleLabel.bounds.size.width, 0,-_closeUpBtn.titleLabel.bounds.size.width)];
    _closeUpBtn.hidden = YES;
     self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, statusBarHeight+_navigationbarH, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-_navigationbarH-40)];
//    UINib *addImgCellNib = [UINib nibWithNibName:@"EFAMatAddImgTCell" bundle:nil];
//    [self.tableView registerNib:addImgCellNib forCellReuseIdentifier:@"EFAMatAddImgTCell"];
    self.tableView.backgroundColor = BG;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedRowHeight = 252.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone; //让tableview不显示分割线
    //多余分割线不显示，（就是隐藏：如果cell的条数不够导致没有吧页面撑满，那么空白部分可能会出现分割线）
//    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//    _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.tableView.frame.size.height, SCREEN_WIDTH,40)];
//    _footerView.backgroundColor = [UIColor whiteColor];
//    self.tableView.tableFooterView  = _footerView;
    
    
    
    
    [self.view sd_addSubviews:@[_closeUpBtn,self.tableView]];
//    [self.tableView reloadData];
    
    if(self.datasCourceVC == 0){
        [self queryAlamIds];
    }else{
        if(self.isOnClickChooseBtn){
            [self queryAllAlamIds];
        }else{
            //没有点击全部按钮，有被选中需要处理的数据
            if(_chooseAlarmArray && _chooseAlarmArray.count > 0){
                _allRows = (int)_chooseAlarmArray.count;
                [self getChooseAlarmArray:0 getRows:1];//进入页面默认显示一条数据
            }
        }
    }
    
}

//获取需要显示在页面上的数据startIndex:起始下标；rows：需要获取多少条数据 从AlarmListVC类中进来，且在AlarmListVC页面中没有点击全选按钮
-(void)getChooseAlarmArray:(int)startIndex getRows:(int)rows{
    for(;startIndex < _chooseAlarmArray.count;startIndex++){
        [_showAlarmArray addObject:_chooseAlarmArray[startIndex]];
        rows--;
        if(rows == 0){
            break;
        }
    }
}

/**
 * 添加报警信息
 * rowSize  添加数据的大小
 */
-(void)addIds:(int)rowSize{
    if(_showAlarmIds == nil || _index >= _showAlarmIds.count || rowSize < 1){
        return;
    }
    NSMutableArray<NSNumber *> *ids = [[NSMutableArray alloc]init];
    int maxIndex =  _index + rowSize;
    if(maxIndex > _showAlarmIds.count){
        maxIndex = (int)_showAlarmIds.count;
    }
    for(; _index < maxIndex; _index++){
        [ids addObject:_showAlarmIds[_index]];
    }
    
    [self queryDada:ids];//查询报警列表数据
}



//查看更多
-(void)onClickMoreBtn{
    if(_allRows > _showAlarmArray.count){
//        [_showAlarmArray addObject:_alarmArray[1]];
        if(!_isOnClickChooseBtn && _datasCourceVC == 1){//在AlarmListVC中没有点击全部选择按钮
            [self getChooseAlarmArray:(int)_showAlarmArray.count getRows:10];
            //如果显示的数据等于总数据 在SeeMoreAlarmBtnCell中会执行方法隐藏《显示更多》按钮
            [self.tableView reloadData];
            //如果显示的数据等于总数据则显示《合上》按钮
        }else{
            [self addIds:10];
        }
        if(self.closeUpBtn.hidden){
             [self showTopBtn];
        }
       
    }else{
        self.closeUpBtn.hidden = NO;
        self.tableView.frame = CGRectMake(0, statusBarHeight+_navigationbarH+40, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-_navigationbarH-40);
    }
   
    
}

//显示“合上”按钮
-(void)showTopBtn{
    self.closeUpBtn.hidden = NO;
    self.tableView.frame = CGRectMake(0, statusBarHeight+_navigationbarH+40, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-_navigationbarH-40);
}

//隐藏“合上”按钮
-(void)hiddenTopBtn{
    _closeUpBtn.hidden = YES;
    self.tableView.frame = CGRectMake(0, statusBarHeight+_navigationbarH, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-_navigationbarH);
    
}


//点击合上按钮
-(void)onclickClose{
    [_showAlarmArray removeAllObjects];
  if(!_isOnClickChooseBtn && _datasCourceVC == 1){
        [self getChooseAlarmArray:0 getRows:1];
        [self hiddenTopBtn];
        [self.tableView reloadData];
    }else{
        _index = 0;//重置下标
        [self addIds:1];
    }
   
}






#pragma mark - UITableViewDataSource



//执行几次tableview（一般看添加几个cell）
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        if(self.showAlarmArray != nil && self.showAlarmArray.count  > 0){
            return self.showAlarmArray.count;
        }
    }else if(section ==1){
        return 1;
    }else if(section == 2){
        return 1;
    }else if(section == 3){
        return 1;
    }
    return 0;
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        AddDisposeAlarmInfoListCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"AddDisposeAlarmInfoListCell" description]];
        if(!cell){
            cell = [[AddDisposeAlarmInfoListCell alloc]init];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setModeDatas:_showAlarmArray[indexPath.row]];
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else if(indexPath.section == 1){
        SeeMoreAlarmBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"SeeMoreAlarmBtnCell" description]];
        if(!cell){
            cell = [[SeeMoreAlarmBtnCell alloc]init];
            __weak typeof(self) weakSelf = self;
            cell.onclickMoerBtn = ^() {
                [weakSelf onClickMoreBtn];
            };
        }
        if(_showAlarmArray.count <= _allRows){
             [cell setBtnTitle:(int)(_allRows-_showAlarmArray.count)];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else if(indexPath.section == 2){
        AddDisposeAlarmCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"AddDisposeAlarmCell" description]];
        if(!cell){
            cell = [[AddDisposeAlarmCell alloc]init];
              __weak typeof(self) weakSelf = self;
            cell.alarmTypeBlock = ^(void){
                [weakSelf jumpToSelectAlarmType];
            };
            
            cell.hiddenDangerBlock = ^(void){
                [weakSelf jumpToSelectAlarmHandle];
            };
            
            cell.localeDisposeBlock = ^(void){
                [weakSelf jumpToSelectInsiteHandle];
            };
            cell.getDisposeTextBlock = ^(NSString* text){
                NSLog(@"输入的内容%@",text);
                weakSelf.pubModel.efairyalarmrecord_content = text;
            };
        }
      
       
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setTypeDatas:_alarmCellArray contentText:_pubModel.efairyalarmrecord_content];
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else if(indexPath.section == 3){
//          EFAMatAddImgTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EFAMatAddImgTCell" forIndexPath:indexPath];
        AddImgCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"AddImgCell" description]];
        if(!cell){
            __weak typeof(self) weakSelf = self;
            cell = [[AddImgCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;//禁止点击cell
            cell.submitBtnBlock = ^(void){
                [weakSelf publishBarBtnTapped];
            };
        }
       
        [cell configViewWithAlarmPubModel:self.pubModel];
        cell.delegate = self;
        return cell;
    }
    return nil;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor whiteColor];
}

//接受点击cell item项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}


//上传图片
- (void)publishBarBtnTapped {
    // 检查用户输入信息
    if (!self.pubModel.efairyalarmrecord_alarm_id) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择报警类型"];
        return;
    }
    //    if (!self.pubModel.efairyalarmrecord_is_handle) {
    //        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择是否完成处理"];
    //        return;
    //    }
    if (self.pubModel.isEmpty) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入内容"];
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.pubModel.isImgUpload) {
        [self requestPublishMaintenance];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    
    [[XDQiniuManager sharedInstance] uploadImages:self.pubModel.imgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.pubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestPublishMaintenance];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}

//发布已处理的报警信息
#pragma mark - network request
- (void)requestPublishMaintenance {
    // 发布报警信息需要登录
    if (![EFAModel sharedInstance].isLogin || _showAlarmIds == nil) {
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
//    NSMutableDictionary *pubDic = [self.pubModel yy_modelToJSONObject];
//    [pubDic removeObjectForKey:@"efairydevicemsg_id_list"];
//    [pubDic removeObjectForKey:@"imgMaxCnt"];
//    [pubDic removeObjectForKey:@"image_list"];
    NSDictionary *alarmrecordInfo = @{@"efairyalarmrecord_alarm_id":@(self.pubModel.efairyalarmrecord_alarm_id),
                                      @"efairyalarmrecord_is_handle":@(self.pubModel.efairyalarmrecord_is_handle),
                                      @"efairyalarmrecord_is_insite_handle":@(self.pubModel.efairyalarmrecord_is_insite_handle),
                                      @"efairyalarmrecord_content":self.pubModel.efairyalarmrecord_content,
                                      };
//    [pubDic setObject:self.pubModel.urlArray forKey:@"efairyalarmrecord_imgurl_list"];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevicealarmstatistics_id_list":_showAlarmIds,
                           @"alarmrecord_info" : alarmrecordInfo,
                           @"alarmrecord_imgurl_list":self.pubModel.urlArray//图片列表
                           };
    
    NSLog(@"发布报警记录的请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiAlarmRecord] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发布报警记录返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"发布成功"];
        temp.completionBlock = ^{
            [self exitViewController];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发布报警记录失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)exitViewController {
    if (self.successHandle) {
        self.successHandle();
        _successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - AddImgCellDelegate
- (void)matAddImgTCell:(AddImgCell *)cell collectionView:(UICollectionView *)collectionView addWithIndexPath:(NSIndexPath *)cIndexPath {
    // 添加照片
    NSInteger maxCnt = self.pubModel.imgMaxCnt - self.pubModel.image_list.count;
    TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
    pickerVC.allowPickingVideo = NO;
    pickerVC.allowTakePicture = NO;
    pickerVC.allowPickingOriginalPhoto = NO;
    [self presentViewController:pickerVC animated:YES completion:nil];
}
- (void)matAddImgTCell:(EFAMatAddImgTCell *)cell collectionView:(UICollectionView *)collectionView delWithIndexPath:(NSIndexPath *)cIndexPath {
    [self.pubModel removePublishItemAtIndex:cIndexPath.row];
    [self.tableView reloadData];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //            [[TZImageManager manager] getOriginalPhotoWithAsset:obj newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            //                NSLog(@"获取原图%@， --%@, (%zd)", photos, info, isDegraded);
            //                if (!isDegraded) {
            //                    [self.pubModel addPublishItemsWithArray:@[photo]];
            //                    [self refreshWholeView];
            //                }
            //            }];
            
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.pubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self.tableView reloadData];
                    }
                }
            }];
        }];
    } else {
        [self.pubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self.tableView reloadData];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    NSLog(@"选择照片缩略图 = %@", photos);
    NSLog(@"选择照片原始的assets = %@", assets);
    NSLog(@"选取照片之后的infos = %@", infos);
}


#pragma mark - private methods
- (void)jumpToSelectAlarmType {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //    NSArray *dataArray = [EFAMtcTypeModel sharedInstance].typeArray;
//     __weak typeof(self) weakSelf = self;
    for (NSDictionary *dic in self.typeArray) {
        [alertVC addAction:[UIAlertAction actionWithTitle:dic[@"alarmTypeName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_alarmCellArray replaceObjectAtIndex:0 withObject:[dic objectForKey:@"alarmType"]];
            self.pubModel.efairyalarmrecord_alarm_id = [[dic objectForKey:@"alarmType"]integerValue];
        [_tableView reloadData];
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)jumpToSelectAlarmHandle {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"隐患是否排除" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_alarmCellArray replaceObjectAtIndex:1 withObject:@(1)];
        self.pubModel.efairyalarmrecord_is_handle = 1;
        [_tableView reloadData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_alarmCellArray replaceObjectAtIndex:1 withObject:@(0)];
         self.pubModel.efairyalarmrecord_is_handle = 0;
        [_tableView reloadData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)jumpToSelectInsiteHandle {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"是否现场处理" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_alarmCellArray replaceObjectAtIndex:2 withObject:@(1)];
         self.pubModel.efairyalarmrecord_is_insite_handle = 1;
        [_tableView reloadData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [_alarmCellArray replaceObjectAtIndex:2 withObject:@(0)];
         self.pubModel.efairyalarmrecord_is_insite_handle = 0;
        [_tableView reloadData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (EFAAlarmPubModel *)pubModel {
    if (!_pubModel) {
        _pubModel = [[EFAAlarmPubModel alloc] init];
        _pubModel.efairydevice_id = self.device_id;
//        _pubModel.efairydevicemsg_id_list = self.showAlarmIds;
        _pubModel.imgMaxCnt = 9;    ///< 最多可以选择9张照片
    }
    return _pubModel;
}

- (NSArray *)typeArray {
    if (!_typeArray) {
        _typeArray = @[@{@"alarmType" : @(1), @"alarmTypeName" : @"火警"},
                       @{@"alarmType" : @(2), @"alarmTypeName" : @"预警"},
                       @{@"alarmType" : @(3), @"alarmTypeName" : @"故障"}];
    }
    return _typeArray;
}



/**
 * 从 AlarmListVC类进来 并且全选执行这个方法
 * 目前isChcekAll参数写死（1），不管是不是全选都设为不全选 0为全不选 1全选
 */
-(void)queryAllAlamIds{
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{
                           @"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.device_id),
                           @"is_check_all" : @"1",
                           @"efairydevicealarmstatistics_id_list":[[NSMutableArray alloc]init],
                           @"alarm_id":self.alarmType == 0? @"" :@(self.alarmType)
                           };
    
    NSLog(@"获取报警编号请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiQueryAlarmIds] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取报警编号成功：%@", responseObject);
        [hud hideAnimated:NO];
        _disposeIdModel = [AlarmNoDispostIdListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        _allRows = (int)_disposeIdModel.total_rows;
        _allRows = _allRows-(int)_notDisposeIds.count;
        _showAlarmIds = _disposeIdModel.efairydevicealarmstatistics_id_list;
        if(_notDisposeIds != nil && _notDisposeIds.count > 0){
            if(_showAlarmIds && _showAlarmIds.count > 0){
                for (NSNumber *num in _notDisposeIds) {
                    [_showAlarmIds removeObject:num];
                }
            }
        }
        [self addIds:1];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取报警编号失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

/**
 * 从 EFAMsgControlTVC 类进来 执行这个方法
 * 从AlarmListVC类进来但是没有全选执行这个方法
 * 目前isChcekAll参数写死，不管是不是全选都设为不全选 0为全不选 1全选
 * msgIdArray 是从EFAMsgControlTVC传过来的报警编号id 用这个id查询真实的报警编号
 */

-(void)queryAlamIds{
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
//    NSMutableDictionary *pubDic = [[NSMutableDictionary alloc]init];
//    [pubDic setObject:self.msgIdArray forKey:@"efairymsg_id_list"];
    NSDictionary *pars = @{
                           @"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.device_id),
                           @"is_check_all" : @"0",
                           @"efairymsg_id_list":self.msgIdArray
                           };
    
    NSLog(@"获取报警编号请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiQueryAlarmIdsById] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取报警编号成功：%@", responseObject);
        [hud hideAnimated:NO];
        _disposeIdModel = [AlarmNoDispostIdListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        _allRows = (int)_disposeIdModel.total_rows;
        _showAlarmIds = _disposeIdModel.efairydevicealarmstatistics_id_list;
        [self addIds:1];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取报警编号失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

-(void)queryDada:(NSMutableArray *)ids{
    if(ids == nil || ids.count == 0){
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{
                           @"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevicealarmstatistics_id_list":[ids yy_modelToJSONString]
                           };
    
    NSLog(@"获取报警信息请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiQueryAlarmInfoByIds] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取报警信息成功：%@", responseObject);
        [hud hideAnimated:NO];
        AlarmListModel * model = [AlarmListModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [_showAlarmArray addObjectsFromArray:model.alarm_msg_list];
        [self.tableView reloadData];
        if(_showAlarmArray.count == _allRows){
            [self showTopBtn];
        }else if(_index <= 1){
            //请把隐藏《合上》按钮 在网络请求完之后执行，要不然可能导致_showAlarmArray[indexPath.row]] 报异常：NSRangeException
             [self hiddenTopBtn];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取报警信息失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


@end
